#ifndef __MYTASK_H__
#define __MYTASK_H__

#include <iostream>
#include <chrono>
#include <thread>
#include <vector>
#include <fstream>
#include <sstream> // 新增

using std::cout;
using std::endl;

class MyTask
{
public:
    virtual void process() = 0;
    virtual ~MyTask() {}
};

// IO密集型任务
class IOTask : public MyTask
{
public:
    void process() override
    {
        auto start = std::chrono::high_resolution_clock::now();
        cout << "IOTask::process() - 开始执行IO密集型任务" << endl;

        // 有意义的IO任务，例如写入和读取文件
        std::ostringstream oss;
        oss << std::this_thread::get_id();
        const std::string filename = "io_task_output_" + oss.str() + ".txt";
        
        // 写入数据到文件
        std::ofstream outfile(filename, std::ios::app);
        if (outfile.is_open()) {
            outfile << "写入一些数据到文件。\n";
            outfile.close();
            cout << "IOTask::process() - 数据已写入到 " << filename << endl;
        } else {
            cout << "IOTask::process() - 无法打开文件 " << filename << " 用于写入。" << endl;
        }
        
        // 读取文件中的数据
        std::ifstream infile(filename);
        if (infile.is_open()) {
            std::string line;
            while (std::getline(infile, line)) {
                // 可以选择处理读取的数据，这里仅仅读取
            }
            infile.close();
            cout << "IOTask::process() - 已读取文件 " << filename << " 中的数据" << endl;
        } else {
            cout << "IOTask::process() - 无法打开文件 " << filename << " 用于读取。" << endl;
        }
      
        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> duration = end - start;
        cout << "IOTask 执行时间: " << duration.count() << " 秒" << endl;
    }
};

// 计算密集型任务
class CPUTask : public MyTask
{
public:
    void process() override
    {
        auto start = std::chrono::high_resolution_clock::now();
        cout << "CPUTask::process() - 开始执行计算密集型任务" << endl;

        // 模拟计算密集型任务，例如计算1到1000000的和
        long long sum = 0;
        for(int i = 1; i <= 1000000; ++i)
        {
            sum += i;
        }
        cout << "CPUTask::process() - 计算结果: " << sum << endl;

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> duration = end - start;
        cout << "CPUTask 执行时间: " << duration.count() << " 秒" << endl;
    }
};

#endif